import { Form, Input, Button, Table, Space, Modal, Select } from 'antd';
import { useForm } from 'antd/es/form/Form';
import { useEffect, useRef, useState } from 'react';
import { getMenuList, deleteMenu } from '@/api';
import { Menu } from '@/types';
import { IAction } from '@/types/modal';
import type { ColumnsType } from 'antd/es/table';
import { message } from '@/utils/AntdGlobal';
import { formatDate } from '@/utils';
import CreateMenu from './createMenu';

export default function MenuList() {
  const [form] = useForm();

  const columns: ColumnsType<Menu.MenuItem> = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
      width: '150px'
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      key: 'icon',
      width: '200px'
    },
    {
      title: '菜单类型',
      dataIndex: 'menuType',
      key: 'menuType',
      render(menuType: number) {
        return formatMenuType(menuType);
      }
    },
    {
      title: '权限标识',
      dataIndex: 'menuCode',
      key: 'menuCode'
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      key: 'path'
    },
    {
      title: '组件路径',
      dataIndex: 'component',
      key: 'component'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(createTime: string) {
        return <span>{formatDate(createTime)}</span>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render(record) {
        return (
          <Space>
            <Button type='text' onClick={handleSubCreate(record)}>
              新增
            </Button>
            <Button type='text' onClick={handleEditor(record)}>
              编辑
            </Button>
            <Button type='text' onClick={handleDelete(record)} danger>
              删除
            </Button>
          </Space>
        );
      }
    }
  ];

  const [data, setData] = useState<Menu.MenuItem[]>([]);

  const formatMenuType = (menuType: number) =>
    ({
      1: '菜单',
      2: '按钮',
      3: '页面'
    })[menuType];

  const menuRef = useRef<{
    open: (
      type: IAction,
      data?: Menu.EditParams | { parentId?: string; orderBy?: number }
    ) => void;
  }>();

  useEffect(() => {
    getMenuData();
  }, []);

  const getMenuData = async () => {
    const data = await getMenuList(form.getFieldsValue());
    setData(data);
  };

  const handleReset = () => {
    form.resetFields();
  };

  const hanldeCreate = () => {
    menuRef.current?.open('create', { orderBy: data.length });
  };

  const handleEditor = (record: Menu.MenuItem) => () => {
    menuRef.current?.open('edit', record);
  };

  const handleSubCreate = (record: Menu.MenuItem) => () => {
    menuRef.current?.open('create', {
      parentId: record._id,
      orderBy: record.children?.length || 0
    });
  };

  const handleDelete = (record: Menu.MenuItem) => () => {
    Modal.confirm({
      title: '删除确认',
      content: (
        <span>
          确定删除该
          {formatMenuType(record.menuType)}
          吗?
        </span>
      ),
      onOk: async () => {
        try {
          await deleteMenu({ _id: record._id });
          message.success('删除成功');
          getMenuData();
        } catch (err) {
          message.error('删除失败');
          console.log(err);
        }
      }
    });
  };

  return (
    <div>
      <Form className='search-form' layout='inline' form={form}>
        <Form.Item label='菜单名称' name='menuName'>
          <Input placeholder='请输入菜单名称'></Input>
        </Form.Item>
        <Form.Item label='菜单状态' name='menuState' style={{ width: 250 }}>
          <Select placeholder='请选择菜单状态'>
            <Select.Option value={1}>正常</Select.Option>
            <Select.Option value={2}>停用</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type='primary' className='mr10' onClick={getMenuData}>
            搜索
          </Button>
          <Button type='default' onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>菜单列表</div>
          <div className='action'>
            <Button type='primary' onClick={hanldeCreate}>
              新增
            </Button>
          </div>
        </div>
        <Table
          bordered
          rowKey='_id'
          columns={columns}
          dataSource={data}
          pagination={false}
        ></Table>
      </div>
      <CreateMenu mRef={menuRef} update={getMenuData}></CreateMenu>
    </div>
  );
}
